import { defineStore } from 'pinia'
import { login, logout, getCurrentUser } from '@/api/auth'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    username: localStorage.getItem('username') || '',
    roleCode: localStorage.getItem('roleCode') || '',
    permissions: [],
    loading: false
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    isAdmin: (state) => state.roleCode === 'admin',
    isNormalUser: (state) => state.roleCode === 'normal_user',
    isBanedUser: (state) => state.roleCode === 'baned_user',
    
    hasPermission: (state) => (permission) => {
      // 如果是管理员，默认拥有所有权限
      if (state.roleCode === 'admin') return true;
      
      return state.permissions.includes(permission)
    }
  },
  
  actions: {
    // 登录
    async loginAction(username, password) {
      try {
        this.loading = true
        console.log('开始登录请求')
        const response = await login({ username, password })
        console.log('登录响应:', response)
        
        if (!response || !response.token) {
          console.error('登录响应中没有token')
          ElMessage.error('登录失败：服务器响应格式错误')
          return false
        }
        
        // 保存登录信息
        this.token = response.token
        this.username = response.username
        this.roleCode = response.roleCode
        
        // 保存到本地存储
        localStorage.setItem('token', this.token)
        localStorage.setItem('username', this.username)
        localStorage.setItem('roleCode', this.roleCode)
        
        console.log('登录信息已保存:', {
          username: this.username,
          roleCode: this.roleCode,
          token: this.token.substring(0, 10) + '...'
        })
        
        // 获取用户权限
        try {
          await this.getUserInfo()
        } catch (err) {
          console.error('获取用户权限失败，但登录状态已保存:', err)
          // 即使获取权限失败，也不影响登录状态
        }
        
        ElMessage.success('登录成功')
        return true
      } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error(error.message || '登录失败')
        return false
      } finally {
        this.loading = false
      }
    },
    
    // 注销
    async logoutAction() {
      try {
        this.loading = true
        await logout()
        
        // 清除用户信息
        this.clearUserInfo()
        
        ElMessage.success('已安全退出')
        return true
      } catch (error) {
        console.error('注销失败:', error)
        // 即使API调用失败，也清除本地信息
        this.clearUserInfo()
        return false
      } finally {
        this.loading = false
      }
    },
    
    // 获取用户信息
    async getUserInfo() {
      try {
        if (!this.token) return null
        
        const response = await getCurrentUser()
        
        // 保存用户权限
        if (response.authorities) {
          this.permissions = response.authorities.map(auth => auth.authority)
        }
        
        return response
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 如果是401错误，清除登录状态
        if (error.response && error.response.status === 401) {
          this.clearUserInfo()
        }
        throw error
      }
    },
    
    // 清除用户信息
    clearUserInfo() {
      this.token = ''
      this.username = ''
      this.roleCode = ''
      this.permissions = []
      
      localStorage.removeItem('token')
      localStorage.removeItem('username')
      localStorage.removeItem('roleCode')
    }
  }
}) 